package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishContriller {
    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增菜品
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        //设置要删除redis的key
        String redisKey="dishList_"+dishDto.getCategoryId();
        redisTemplate.delete(redisKey);
        return R.success("新增菜品成功");
    }

    /**
     * 分页查询
     *
     * @return
     */
    //http://localhost:8080/dish/page?page=1&pageSize=10
    @GetMapping("/page")
    public R<Page> page(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "name", defaultValue = "") String name
    ) {
        //封装分页对象
        Page<Dish> dishPage = new Page<>(page, pageSize);

        Page<DishDto> dishDtoPage = new Page<>();

        //设置条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.hasLength(name), Dish::getName, name);
        //分页查询
        Page<Dish> PageInfo = dishService.page(dishPage, queryWrapper);

        BeanUtils.copyProperties(PageInfo, dishDtoPage, "records");

        List<Dish> records = dishPage.getRecords();

        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        }).collect(Collectors.toList());


        dishDtoPage.setRecords(list);

        return R.success(dishDtoPage);
    }


    /**
     * 给网页修改菜品回传信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable("id") Long id) {
        //查询菜品对象
//        Dish dish = dishService.getById(id);
        DishDto dishDto = dishService.getWithFlavor(id);
        //设置要删除redis的key
        String redisKey="dishList_"+dishDto.getCategoryId();
        redisTemplate.delete(redisKey);
        return R.success(dishDto);
    }

    /**
     * 修改菜品
     *
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //调用方法
        dishService.updateWithFlavor(dishDto);
        //设置要删除redis的key
        String redisKey="dishList_"+dishDto.getCategoryId();
        redisTemplate.delete(redisKey);
        return R.success("修改成功");
    }


    /**
     * 批量修改状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    public R<String> updatestatus(
            @PathVariable("status") Integer status,
            @RequestParam("ids") Long[] ids
    ) {

        List<Dish> dishList = Arrays.stream(ids).map((item) -> {
            Dish dish = new Dish();
            dish.setId(item);
            dish.setStatus(status);
            return dish;
        }).collect(Collectors.toList());
        dishService.updateBatchById(dishList);
       /* //设置要删除redis的key
        String redisKey="dishList_*";
        redisTemplate.delete(redisKey);*/

        return R.success("修改成功");
    }

    //http://localhost:8080/dish?ids=1517478405015162882,1494608316105572354
    @DeleteMapping
    public R<String> deleteByIds(@RequestParam("ids") List<Long> ids){

        dishService.deleteWithFlavor(ids);
       /* //设置要删除redis的key
        String redisKey="dishList_*";
        redisTemplate.delete(redisKey);*/
        return R.success("删除成功");

    }

    //http://localhost:8080/dish/list?categoryId=1413384954989060097
    /**
     * 根据id返回集合
     * @param dish
     * @return
     */
    /*@GetMapping("/list")
    public R< List<Dish>> list(Dish dish){
        //查询type为1时
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);

        //按sort降序来排序
        queryWrapper.orderByDesc(Dish::getSort);

        //查询
        List<Dish> dishList = dishService.list(queryWrapper);
        return R.success(dishList);
    }*/

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){

       String redisKey="dishList_"+dish.getCategoryId();
        //如果缓存里面有 就直接返回 不需要查
        List<DishDto> redisDishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        //判断是否有值
        if(redisDishDtoList!=null){
            return R.success(redisDishDtoList);
        }
        //查询type为1时
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        queryWrapper.eq(Dish::getStatus,1);

        //按sort降序来排序
        queryWrapper.orderByDesc(Dish::getSort);
        //查询
        List<Dish> dishList = dishService.list(queryWrapper);

        List<DishDto> dishDtoList = dishList.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            Category category = categoryService.getById(item.getCategoryId());
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
            dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
            dishDto.setFlavors(list);
            return dishDto;
        }).collect(Collectors.toList());

        //将查询到的集合放到redis缓存中
        redisTemplate.opsForValue().set(redisKey,dishDtoList,30, TimeUnit.MINUTES);


        return R.success(dishDtoList);
    }


}
